//
//  QYXFindMoreViewController.m
//  OpenYourEyes
//
//  Created by dllo on 16/6/6.
//  Copyright © 2016年 Google AdWords. All rights reserved.
//

#import "QYXFindMoreViewController.h"
#import "HYBLoopScrollView.h"
#import "QYXFindMoreModel.h"
#import "QYXFindMoreCollectionViewCell.h"
#import "QYXUICollectionView.h"
#import "QYXFindMoreAuthor.h"
#import "QYXFindTopicCategoryVc.h"
#import "QYXFindMoreSingleVC.h"
#import "QYXMoreAuthorVC.h"
#import "QYXAuthorSigleVC.h"
#import "QYXPicOnlyViewController.h"
#import "QYXCardViewController.h"
#import "AppDelegate.h"

#define kDissCovreURL @"http://baobab.wandoujia.com/api/v3/discovery?_s=d4adf1770ea9560be108dbe7c83ef85e&f=iphone&net=wifi&u=ebe4ca1f9d83e4dc4f915b0495e6e1946ee0eb93&v=2.2.0&vc=721"


@interface QYXFindMoreViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, WMPageControllerDelegate>

/** 轮播图数组 */
@property (nonatomic, strong) NSMutableArray *cycleArr;
@property (nonatomic, strong) NSMutableArray *cycleArrUrl;

/** 优质作者数组 */
@property (nonatomic, strong) NSMutableArray *authorArr;

/** 优质作者数组 */
@property (nonatomic, strong) NSMutableArray *topicArr;

/** 轮播图视图 */
@property (nonatomic, strong) HYBLoopScrollView *cycleView;


/** CollectionView */
@property (nonatomic, strong) QYXUICollectionView *collectionView;
@end

@implementation QYXFindMoreViewController

- (void)loadView
{
    [super loadView];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"123456"] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth / 4, 44)];
    titleLabel.text = @"Eyepelizer";
    titleLabel.textAlignment = 1;
    titleLabel.font = [UIFont fontWithName:@"Lobster 1.4" size:25];
    self.navigationItem.titleView = titleLabel;

       self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"search"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(search)];
    
    [self creatCollectionView];
    [self requiredData];
}


#pragma mark - 搜索

- (void)search
{
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 定时器

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [self.cycleView startTimer];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
    [self.cycleView pauseTimer];
}


#pragma mark - 创建CollectionView

- (void)creatCollectionView
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    float size = (kScreenWidth -1) *0.5;
    flowLayout.itemSize = CGSizeMake(size , size);
    flowLayout.minimumLineSpacing = 1;
    flowLayout.minimumInteritemSpacing = 1;
    
    self.collectionView = [[QYXUICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowLayout];
    [self.view addSubview:_collectionView];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    flowLayout.headerReferenceSize = CGSizeMake(kScreenWidth, 423 *KFitHeight);
    [self.collectionView registerNib:[UINib nibWithNibName:@"QYXFindMoreCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"FindMore"];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
}

#pragma mark - CollectionDelegate

-  (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    QYXFindMoreCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"FindMore" forIndexPath:indexPath];
    cell.model = self.topicArr[indexPath.row];
    
    return cell;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.topicArr.count;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    QYXFindMoreModel *model = _topicArr[indexPath.row];

    if (model.id == 0) {
        
        QYXPicOnlyViewController *vc = [[QYXPicOnlyViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        return;
        
    }
    
    NSArray *pageArray = @[[QYXFindMoreSingleVC class], [QYXFindMoreSingleVC class]];
    NSArray *title = @[@"按时间排序", @"分享排行榜"];
    QYXFindTopicCategoryVc *vc = [[QYXFindTopicCategoryVc alloc] initWithViewControllerClasses:pageArray andTheirTitles:title];
    vc.delegate = self;
    vc.menuViewStyle = WMMenuViewStyleLine;
    vc.menuItemWidth = 100;
    vc.progressHeight = 1;
    vc.menuViewBottomSpace = 3;
    vc.titleSizeSelected = 16;
    vc.menuBGColor = [UIColor whiteColor];
    vc.progressColor = [UIColor colorWithWhite:0.000 alpha:0.296];
    vc.titleSizeNormal = 14;
    vc.titleColorNormal = [UIColor blackColor];
    vc.titleColorSelected = [UIColor blackColor];
    
    vc.ID = model.id;
    vc.titleStr = model.title;
   
    [self.navigationController pushViewController:vc animated:YES];
}



- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    

    UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
    
     __unsafe_unretained __typeof(self) weakSelf = self;
    
    self.cycleView = [HYBLoopScrollView loopScrollViewWithFrame:CGRectMake(0, 0, kScreenWidth, 240 * KFitHeight) imageUrls:self.cycleArrUrl timeInterval:5 didSelect:^(NSInteger atIndex) {
        
        QYXCardViewController *vc = [[QYXCardViewController alloc] init];
        AppDelegate *tempDelegate = [UIApplication sharedApplication].delegate;
        tempDelegate.tabBar.backView.hidden = YES;
        [weakSelf.navigationController pushViewController:vc animated:YES];
        
    } didScroll:^(NSInteger toIndex) {
        
    }];
    
    _cycleView.backgroundColor = [UIColor whiteColor];
    _cycleView.shouldAutoClipImageToViewSize = NO;
    _cycleView.placeholder = kPlaceHolderImage;
    _cycleView.alignment = kPageControlAlignCenter;
    
    [view addSubview:_cycleView];
    
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, self.cycleView.frame.origin.y + self.cycleView.frame.size.height, kScreenWidth, 30)];
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont fontWithName:@"FZLTZCHJW--GB1-0" size:15];
    label.textColor = [UIColor colorWithWhite:0.000 alpha:0.612];
    label.text = @"－ 优 质 作 者 －";
    [view addSubview:label];
    float size = kScreenWidth / 4;
    for (NSInteger i = 0; i < 4; i++) {
        QYXFindMoreModel *model = self.authorArr[i];
        QYXFindMoreAuthor *authorView = [[QYXFindMoreAuthor alloc] initWithFrame:CGRectMake(size * i, label.frame.size.height + label.frame.origin.y,  size, (size + 20) *KFitHeight) WithPicUrl:model.icon WithTitle:model.name];
        [view addSubview:authorView];
        
        if (i == 0) {
            UILabel *moreDataLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, authorView.frame.size.height + authorView.frame.origin.y, kScreenWidth, 423 *KFitHeight - authorView.frame.size.height - authorView.frame.origin.y)];
            moreDataLabel.textAlignment = NSTextAlignmentCenter;
            moreDataLabel.font = [UIFont fontWithName:@"Helvetica-BoldOblique" size:13];
            moreDataLabel.text = @"查 看 更 多";
            moreDataLabel.textColor = [UIColor grayColor];
            [view addSubview:moreDataLabel];
            moreDataLabel.layer.borderWidth = 1;
            moreDataLabel.userInteractionEnabled = YES;
            moreDataLabel.layer.borderColor = [UIColor colorWithWhite:0.000 alpha:0.047].CGColor;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(moreTap:)];
            [moreDataLabel addGestureRecognizer:tap];

        }
        authorView.userInteractionEnabled = YES;
        authorView.tag = 100 + i;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(authorTap:)];
        
        [authorView addGestureRecognizer:tap];
    }
    
    
    return view;
}

#pragma mark - 查看更多手势

- (void)moreTap:(UITapGestureRecognizer *)tap
{
    QYXMoreAuthorVC *vc = [[QYXMoreAuthorVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)authorTap:(UITapGestureRecognizer *)tap
{
    QYXFindMoreAuthor *sortView = (QYXFindMoreAuthor *)tap.view;
    NSInteger tag = sortView.tag - 100;
     QYXFindMoreModel *model = self.authorArr[tag];
    
    QYXAuthorSigleVC *vc = [[QYXAuthorSigleVC alloc] init];
    vc.model = model;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 请求数据

- (void)requiredData
{
    [QYXNetTool getNetWithUrl:kDissCovreURL urlBody:nil header:nil response:QYXJSON success:^(id result) {
        
        NSArray *arr = result[@"itemList"];
        
        self.topicArr = [NSMutableArray array];
        for (NSDictionary *d in arr) {
            
            NSString *str = d[@"type"];
     
            if ([str isEqualToString:@"horizontalScrollCard"]) {
                self.cycleArrUrl = [NSMutableArray array];
                self.cycleArr = [NSMutableArray array];
                for (NSDictionary *dic in d[@"data"][@"itemList"]) {
                    QYXFindMoreModel *model = [[QYXFindMoreModel alloc] init];
                    [model setValuesForKeysWithDictionary:dic[@"data"]];
                    [self.cycleArrUrl addObject:model.image];
                    [self.cycleArr addObject:model];
//                    NSLog(@"model.image -> %@", model.image);
                }
            }
            else if ([str isEqualToString:@"topPgc"])
            {
                self.authorArr = [NSMutableArray array];
                
                for (NSDictionary *dic in d[@"data"][@"pgcList"]) {
                    QYXFindMoreModel *model = [[QYXFindMoreModel alloc] init];
                    [model setValuesForKeysWithDictionary:dic];
                    [self.authorArr addObject:model];
                }
//                NSLog(@"self.authorArr -> %@", self.authorArr);

            }
            else
            {
                    QYXFindMoreModel *model = [[QYXFindMoreModel alloc] init];
                    [model setValuesForKeysWithDictionary:d[@"data"]];
                    [self.topicArr addObject:model];
             }
       }
//        NSLog(@"self.topicArr -> %@", self.topicArr);
        // 刷新
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.collectionView reloadData];
        });
        

        
    } failure:^(NSError *error) {
        
    }];
}



@end
